﻿using System;
using System.Data;
using Domain.NHibernate.Models;
using NHibernate;

namespace Web.Logic.Models.UnitOfWorkClasses
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ISession session;
        private readonly GenericTransaction transaction;
        private bool isCommited;

        internal UnitOfWork(ISession session)
        {
            this.session = session;
            transaction = new GenericTransaction(session.BeginTransaction(IsolationLevel.ReadCommitted));
        }

        public void Dispose()
        {
            if (isCommited == false)
                try
                {
                    transaction.Rollback();
                }
                finally
                {
                    transaction.Dispose();
                }

            session.Dispose();
        }

        public IGenericTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            return new GenericTransaction(session.BeginTransaction(isolationLevel));
        }

        public void Commit()
        {
            try
            {
                transaction.Commit();
                isCommited = true;
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                transaction.Dispose();
            }
        }

        public ISessionAdapter GetSessionAdapter()
        {
            return new SessionAdapter(session);
        }
    }
}